import {defineStore} from "pinia";
//默认访问 index.ts
import {CaptchaData, getCaptchaData, LoginParam, doLogin, UserInfoData, getUserInfoData} from "@/api/user";

// 用户登录模块
interface UserInfoStoreStateData {
    captchaData: CaptchaData
    loginParam: LoginParam
    token: string
    userInfoData: UserInfoData
}

let userInfoStore = defineStore("userInfo", {
    state: (): UserInfoStoreStateData => {
        return {
            captchaData: {
                image: "",
                key: ""
            },
            loginParam: {
                username: "user",
                password: "123456",
                captchaKey: "",
                captchaCode: ""
            },
            token: localStorage.getItem("token") || "",
            userInfoData: {
                name: "",
                avatarUrl: ""
            }
        }
    },
    getters: {},
    actions: {
        //todo 1. 获取验证码
        async getCaptcha() {
            await getCaptchaData()
            {
                let {data} = await getCaptchaData()
                this.captchaData = data
            }
        },
        //todo 2. 验证登录
        async checkLogin() {
            this.loginParam.captchaKey = this.captchaData.key
            let {data} = await doLogin(this.loginParam)
            this.token = data
            localStorage.setItem("token", this.token)
        },
        //todo 3. 获取登录用户信息
        async getUserInfo() {
            let {data} = await getUserInfoData()
            this.userInfoData = data
        },
        //todo 4. 退出登录
        /*async */logout() {
            this.token = ""
            this.userInfoData = {
                name: "",
                avatarUrl: ""
            }
            localStorage.removeItem("token")
        }
    }
})

export default userInfoStore;